<template>
  <div class="home">
    <div class="wrap">
      <!-- 商户信息 -->
      <div
        style="
          border-right: 1px solid #f0f0f0;
          height: 200px;
          margin-top: 41px;
          padding-left: 30px;
          padding-right: 30px;
        "
      >
        <div class="logoBox">
          {{
            companyInfo1.memberName ? companyInfo1.memberName.slice(0, 1) : "公"
          }}
        </div>
        <div class="company" :title="companyInfo1.memberName">
          {{ companyInfo1.memberName ? companyInfo1.memberName : "公司名称" }}
        </div>
        <div v-if="companyInfo1.merchantInfoComplete == 'success'">
          {{ companyInfo1.address ? companyInfo1.address : "" }}
        </div>
        <el-button
          @click="toRegis"
          :disabled="
            companyInfo1.merchantInfoComplete == 'wait' ||
            companyInfo1.merchantInfoComplete == 'processing'
          "
          v-if="
            companyInfo1.merchantInfoComplete == 'create' ||
            companyInfo1.merchantInfoComplete == 'wait' ||
            companyInfo1.merchantInfoComplete == 'processing' ||
            companyInfo1.merchantInfoComplete == 'fail' ||
            companyInfo1.merchantInfoComplete == 'refuse'
          "
          >{{
            companyInfo1.merchantInfoComplete == "create"
              ? "请完善企业信息"
              : companyInfo1.merchantInfoComplete == "wait" ||
                companyInfo1.merchantInfoComplete == "processing"
              ? "资料审核中"
              : "请修改企业信息"
          }}</el-button
        >
      </div>
      <!-- 服务信息 -->
      <div class="box" v-for="(v, i) in serviceProductData" :key="i">
        <img
          :src="require(`@/assets/imgs/middleWork/${v.serviceIcon}.png`)"
          v-if="
            v.serviceIcon == 'one' ||
            v.serviceIcon == 'two' ||
            v.serviceIcon == 'three'
          "
        />
        <img :src="host + `/merchantApi/oss/view?id=${v.serviceIcon}`" v-else />
        <div class="title">
          {{ v.serviceName }}
          <span class="tag" v-if="v.isBuy && !v.isExpire && v.versionFlag">{{
            v.mealName
          }}</span>
        </div>
        <div>{{ v.serviceDesc }}</div>
        <div class="date">
          <div v-if="v.isBuy">
            <div v-if="v.isExpire">
              <div>已过期 {{ v.expireDays }} 天</div>
              <el-link type="success" @click="goBuy()" v-if="!v.isSubCorp"
                >续费</el-link
              >
              <!-- <el-link
                type="success"
                @click="$router.push('/qiye/accountView')"
                >{{ v.versionFlag == 1 ? "升级/续费" : "续费" }}</el-link
              > -->
            </div>
            <div v-else>
              <div class="date">有效日期至 {{ v.expireDateStr }}</div>
            </div>
          </div>
          <div v-if="!v.isBuy && !v.isSubCorp">
            <el-link type="success" @click="goBuy()">申请开通服务</el-link>
          </div>
        </div>
      </div>
    </div>

    <!-- 应用信息 -->
    <div class="addWrap">
      <div
        class="item"
        v-for="(value, index) in appData"
        :key="index"
        @click="showMerchant(value.id)"
      >
        <!-- <div class="removeBox" v-if="getUserInfo().userType == 'main_admin'" @click.stop>
          <el-tooltip effect="dark" placement="bottom-start" >
            <div slot="content" @click.stop="deleteApp(value)" style="cursor: pointer;">删除</div>
            <i class="el-icon-more"></i>
          </el-tooltip>
        </div> -->
        <div style="height: 50px">
          <div class="nameBox">
            <span class="name">{{ value.appName }}</span>
            <span
              class="editIcon"
              @click.stop="editCodeApp(value)"
              v-if="
                getUserInfo().userType == 'main_admin' ||
                getUserInfo().userType == 'main_user'
              "
              ><i class="el-icon-edit-outline"></i>
            </span>
          </div>
          <div style="font-size: 12px; color: #bfbfbf">
            ID:
            <span
              style="
                width: 220px;
                overflow: hidden;
                display: inline-block;
                position: relative;
                top: 3px;
              "
            >
              {{ value.id }}
            </span>
            <img
              src="@/assets/imgs/middleWork/icon_copy.png"
              style="
                width: 14px;
                height: 14px;
                float: right;
                position: relative;
                top: 3px;
              "
              @click.stop="copyAppId(value.id)"
            />
          </div>
        </div>

        <div class="money" v-if="value.enableChannel">
          <div style="margin-right: 50px">
            <div>累计收款</div>
            <div class="number">¥{{ value.orderAmountTotal || 0.0 }}</div>
          </div>
          <!-- <div>
            <div>分账金额/元</div>
            <div class="number">¥{{ value.settleAmountTotal || 0.0 }}</div>
          </div> -->
          <div>
            <div>累计交易量/笔</div>
            <div class="number">{{ value.orderTotal || 0.0 }}</div>
          </div>
        </div>
        <div class="money" v-else>
          <div
            class="number"
            style="color: #03bfc6; margin-top: 18px"
            @click.stop="showMerchant1(value.id, '/setting/payDitch')"
          >
            前往配置支付渠道
          </div>
        </div>
      </div>
      <div
        class="item add"
        @click="addApp()"
        v-if="
          getUserInfo().userType == 'main_admin' ||
          getUserInfo().userType == 'main_user'
        "
      >
        <div>
          <img src="@/assets/imgs/middleWork/add.png" class="addIcon" />
        </div>
        <div class="addText">添加应用</div>
      </div>
    </div>
    <RegisterDialogVue
      v-if="dialogVisible"
      :dialogVisible.sync="dialogVisible"
      :info="companyInfo"
      @changeInfo="showDialog"
      @changeInfo1="changeInfo1"
    />
    <el-dialog
      title=""
      class="addDialog"
      :visible.sync="addDialog"
      width="449px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialogTitle">{{ isEditApp ? "编辑应用" : "添加应用" }}</div>

      <el-form
        :model="form"
        label-position="top"
        @submit.native.prevent
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item label="应用名称" prop="appName">
          <el-input
            v-model="form.appName"
            maxlength="32"
            show-word-limit
            placeholder="输入应用名称"
            autocomplete="off"
            @keyup.enter.native="handleAdd('ruleForm')"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="
            $refs['ruleForm'].resetFields();
            addDialog = false;
          "
          class="width120"
          >取消</el-button
        >
        <el-button
          type="primary"
          class="width120"
          @click="handleAdd('ruleForm')"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <codeDialogVue
      codeId="2"
      type="SMS_BUSINESS_EDIT_APP_NAME"
      :codeDialog.sync="codeDialog"
      @codeState="codeStateFn"
    />
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import { isCnEnNum } from "@/utils/validate";
import RegisterDialogVue from "./registerDialog.vue";
import codeDialogVue from "@/components/codeDialog.vue";
import { getUserInfo, setUserInfo } from "@/utils/public";
import { mapState } from "vuex";

export default {
  name: "middleWorkHome",
  components: {
    // headerNav,
    RegisterDialogVue,
    codeDialogVue,
  },
  computed: {
    ...mapState(["regisMessCommand"]),
  },
  data() {
    const testComName = (rule, value, callback) => {
      if (isCnEnNum(value)) {
        callback();
      } else {
        callback(new Error("请输入中/英文字符，不支持特殊字符"));
      }
    };
    return {
      listNum: "",
      host: window.location.origin,
      value1: false,
      dialogVisible: false,
      addDialog: false,
      codeItem: {},
      codeDialog: false,
      form: {
        appId: 0,
        appName: "",
      },
      isEditApp: false,
      appData: [],
      companyInfo: {},
      companyInfo1: {},
      serviceProductData: [],
      rules: {
        appName: [
          { required: true, message: "请输入应用名称", trigger: "change" },
          {
            validator: testComName,
            trigger: "change",
          },
          { max: 32, message: "最大长度32字符", trigger: "change" },
          { min: 2, message: "最小长度2字符", trigger: "change" },
        ],
      },
    };
  },
  async created() {
    // this.alertRegisterMess();
    // 获取商户信息
    this.refreshCurrentUser();

    this.getAppData();
    this.$store.commit("changeAppId", "");
    this.getServiceProduct();

    //子商户登录（未注册）提示
    if (
      getUserInfo().userType != "main_user" &&
      getUserInfo().userType != "main_admin"
    ) {      
      let isRegis = await this.$getMechantUserRegisInfo();
      if (isRegis == "create") {
        //未注册
        this.changeRegisText({
          tit: "请先完善企业信息后方可使用",
          btn: "去完善",
        });
        this.$store.commit("changeRegisMess", true);
        setTimeout(() => {
          this.$store.commit("changeRegisMess", false);
        }, 5000);
      }
    }
  },
  methods: {
    ...mapMutations(["changeRegisMess", "changeRegisText"]),
    getUserInfo,
    changeInfo1() {
      this.refreshCurrentUser();
    },
    async toRegis() {
      console.log(123)
      let isRegis = await this.$getMechantUserRegisInfo();
      console.log(isRegis);
      if (isRegis != "success") {
        if (isRegis == "create") {
          //未注册
          this.changeRegisText({
            tit: "请先完善企业信息，审核通过后方可使用",
            btn: "去完善",
          });
          this.$router.push({
            path: "/companyPersonInfo",
            query: { command: this.regisMessCommand },
          });
        } else if (isRegis == "wait" || isRegis == "processing") {
          //审核中
          this.changeRegisText({
            tit: "资料审核中，请稍候再试",
            btn: "",
          });
          this.$store.commit("changeRegisMess", true);
          setTimeout(() => {
            this.$store.commit("changeRegisMess", false);
          }, 3000);
        } else if (isRegis == "fail" || isRegis == "refuse") {
          //审核失败,拒绝
          this.changeRegisText({
            tit: "企业信息审核未通过，请前往修改",
            btn: "去修改",
            command: 1,
          });
          this.$router.push({
            path: "/companyPersonInfo",
            query: { command: this.regisMessCommand },
          });
        }
      }
    },
    copyAppId(value) {
      const input = document.createElement("input"); // 创建input对象
      input.value = value; // 设置复制内容
      document.body.appendChild(input); // 添加临时实例
      input.select(); // 选择实例内容
      document.execCommand("Copy"); // 执行复制
      document.body.removeChild(input); // 删除临时实例
      this.$message.success("复制成功！");
    },
    editCodeApp(value) {
      if (getUserInfo().checkFlag) {
        this.editApp(value);
      } else {
        this.codeItem = value;
        this.codeDialog = true;
      }
    },
    codeStateFn(val) {
      if (val) {
        this.editApp(this.codeItem);
      }
    },
    editFn() {
      if (
        getUserInfo().userType == "sub_admin" ||
        getUserInfo().userType == "main_admin"
      ) {
        this.dialogVisible = true;
      } else {
        this.$message.closeAll();
        this.$message.warning("商户信息 暂无权限修改");
      }
      // if (getUserInfo().merchantInfoComplete == "in_complete") {
      //   this.$message.closeAll();
      //   this.$message.warning("商户信息审核中 暂不能修改");
      // } else {
      //   this.$message.closeAll();
      //   this.$message.warning("商户信息 暂不能修改");
      // }
    },
    refreshCurrentUser() {
      this.$http.post("/sys/user/refreshCurrentUser").then((res) => {
        if (res.code === "0000") {
          console.log(res.data);
          setUserInfo({ ...res.data });
          this.companyInfo1 = res.data;
          // this.showDialog();
        }
      });
    },
    showDialog() {
      let user = getUserInfo();
      // 信息没有完善 必须完善信息
      if (user.merchantInfoComplete == "wait_complete") {
        this.alertRegisterMess();
        // this.dialogVisible = true;
      } else if (user.merchantInfoComplete == "in_complete") {
        this.getCompanyInfo1();
      }
    },
    getCompanyInfo1() {
      this.$http.get("/api/merchant/memberinfo/get").then((res) => {
        if (res.code === "0000") {
          console.log(res.data);
          this.companyInfo = res.data;
          // setTimeout(() => {
          //   this.dialogVisible = true;
          // }, 100);
        }
      });
    },
    getServiceProduct() {
      this.$http.get("/sys/meal/listMeal").then((res) => {
        if (res.code === "0000") {
          console.log(res.data);
          this.serviceProductData = res.data;
          // mock服务
          // this.serviceProductData = [
          //   ...this.serviceProductData,
          //   {
          //     creator: null,
          //     expireDateStr: "2024-09-13 18:29:21",
          //     expireDays: null,
          //     id: "eqz940_15557d8c85484ace8b732b6b5ccee2d9",
          //     isBuy: true,
          //     isExpire: false,
          //     isSubCorp: false,
          //     mealAmount: null,
          //     mealId: "ao10aq_0075b78a1c6e4b52847f2bea8361593f",
          //     mealName: "测试",
          //     mealSort: null,
          //     mealType: "charge",
          //     serviceDesc: "整合全渠道支付收款",
          //     serviceIcon: "65376bee503a800001b85067",
          //     serviceName: "测试服务1",
          //     updater: null,
          //     versionFlag: true,
          //   },
          //   {
          //     creator: null,
          //     expireDateStr: "2024-09-13 18:29:21",
          //     expireDays: null,
          //     id: "eqz940_15557d8c85484ace8b732b6b5ccee2d9",
          //     isBuy: true,
          //     isExpire: false,
          //     isSubCorp: false,
          //     mealAmount: null,
          //     mealId: "ao10aq_0075b78a1c6e4b52847f2bea8361593f",
          //     mealName: "测试",
          //     mealSort: null,
          //     mealType: "charge",
          //     serviceDesc: "整合全渠道支付收款",
          //     serviceIcon: "65376bee503a800001b85067",
          //     serviceName: "测试服务2",
          //     updater: null,
          //     versionFlag: true,
          //   },
          // ];
        }
      });
    },
    deleteApp(app) {
      const info = getUserInfo();
      if (info.userType === "main_admin") {
        this.$confirm(`你确定删除 ${app.appName} 应用?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          customClass: "confirm",
          type: "warning",
          center: true,
        }).then(() => {
          this.$http.delete("api/app/delete/" + app.id).then((res) => {
            if (res.code === "0000") {
              this.$message.success(`删除 ${app.appName} 应用成功`);
              this.getAppData();
            } else {
              this.$message.error(`删除 ${app.appName} 应用失败`);
            }
          });
        });
      } else {
        this.$message.warning("暂无权限，请联系管理员！");
      }
    },
    async checkRegis() {
      let isRegis = await this.$getMechantUserRegisInfo();
      console.log(isRegis);
      if (isRegis != "success") {
        if (isRegis == "create") {
          //未注册
          this.changeRegisText({
            tit: `${
              getUserInfo().userType == "main_user" ||
              getUserInfo().userType == "main_admin"
                ? "请先完善企业信息，审核通过后方可使用"
                : "请先完善企业信息后方可使用"
            }`,
            btn: "去完善",
          });
        } else if (isRegis == "wait" || isRegis == "processing") {
          //审核中
          this.changeRegisText({
            tit: "资料审核中，请稍候再试",
            btn: "",
          });
        } else if (isRegis == "fail" || isRegis == "refuse") {
          //审核失败,拒绝
          this.changeRegisText({
            tit: "企业信息审核未通过，请前往修改",
            btn: "去修改",
            command: 1,
          });
        }
        this.$store.commit("changeRegisMess", true);
        setTimeout(() => {
          this.$store.commit("changeRegisMess", false);
        }, 3000);
        return false;
      } else {
        return true;
      }
    },
    async addApp() {
      let isRegis = await this.checkRegis();
      if (isRegis) {
        // 已注册
        this.$http.post("/api/app/getMealLimitAppNumber").then((res) => {
          if (res.code === "0000") {
            const info = getUserInfo();
            if (
              info.userType === "main_admin" ||
              info.userType === "main_user"
            ) {
              if (this.appData.length >= res.data) {
                return this.$message.error(`最多创建${res.data}个应用！`);
              } else {
                this.form = {
                  appId: 0,
                  appName: "",
                };
                this.addDialog = true;
                this.isEditApp = false;
              }
            } else {
              this.$message.warning("暂无权限，请联系管理员！");
            }
          }
        });
      }
    },
    async goBuy() {
      let isRegis = await this.checkRegis();
      if (isRegis) {
        this.$router.push("/qiye/accountView");
      }
    },
    async showMerchant(id) {
      let isRegis = await this.checkRegis();
      if (isRegis) {
        this.$store.commit("resetState", {
          menuType: 1, //结算菜单
          path: "0",
          appId: id,
          checkedMenuItem: {
            index: "1-0",
            children: [],
          },
        });
        const list = this.$store.state.merchantMenu[0];
        this.$router.push(
          list.children.length ? list.children[0].url : list.url
        );
        sessionStorage.removeItem("checkedMenuItem");
        localStorage.setItem("appId", id);
        this.$store.commit("changeShowChildMenu", false);
      }
    },
    async showMerchant1(id, url) {
      let isRegis = await this.checkRegis();
      if (isRegis) {
        if (this.$store.state.merchantMenu.length) {
          this.$store.state.merchantMenu.forEach((e) => {
            if (e.children.length) {
              e.children.forEach((c) => {
                if (c.url == url) {
                  localStorage.setItem("appId", id);
                  this.$router.push(c.url);
                }
              });
            }
          });
        }
      }
    },
    handleAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http
            .post(this.form.appId === 0 ? "api/app/add" : `api/app/update`, {
              ...this.form,
            })
            .then((res) => {
              if (res.code === "0000") {
                this.$message.success(
                  this.form.appId === 0 ? "添加应用成功" : "修改应用成功"
                );
                this.$refs["ruleForm"].resetFields();
                this.addDialog = false;
                this.getAppData();
              } else {
                this.addDialog = true;
              }
            });
        } else {
          return false;
        }
      });
    },
    editApp(app) {
      const info = getUserInfo();
      if (info.userType === "main_admin" || info.userType === "main_user") {
        let editApp = {};
        Object.assign(editApp, app);
        this.form = editApp;
        this.addDialog = true;
        this.isEditApp = true;
      }
    },
    getAppData() {
      this.$http.get("/api/app/get").then((res) => {
        if (res.code === "0000") {
          this.appData = res.data;
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  min-width: 1400px;
  //   background: #f9f9f9;
  //   .header {
  //     display: flex;
  //     justify-content: space-between;
  //     align-items: center;
  //     background: #fff;
  //     box-shadow: 0px 3px 7px 0px rgba(0, 0, 0, 0.05);
  //     padding: 0 44px;
  //     border-bottom: 1px solid #eee;
  //     .logo {
  //       width: 235px;
  //       height: 42px;
  //     }
  //   }

  .wrap {
    display: flex;
    justify-content: space-between;
    height: 280px;
    color: #869daa;
    background: #fff;

    div {
      flex: 1;
      text-align: center;

      .logoBox {
        border-radius: 6px;
        width: 72px;
        height: 72px;
        background: #1d1c1c;
        margin: 25px auto 30px;
        color: #ffffff;
        font-size: 30px;
        text-align: center;
        line-height: 72px;
      }

      .company {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        font-size: 18px;
        margin-bottom: 10px;
        font-weight: 500;
        color: #4f595f;
      }

      .editText {
        font-size: 14px;
        color: #666666;
        width: 92px;
        height: 34px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #bfbfbf;
        line-height: 34px;
        margin: 40px auto 0;
        cursor: pointer;
      }
    }

    .title {
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #4f595f;
      margin: 10px 0;
    }

    .box {
      padding-top: 45px;

      img {
        width: 70px;
        height: 67px;
      }

      .tag {
        display: inline-block;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        line-height: 16px;
        padding: 0 10px;
        position: relative;
        top: -3px;
        height: 18px;
        background: #869daa;
        border-radius: 2px;
      }
      .tag1 {
        width: 90px;
        border-radius: 4px;
        font-weight: 500;
        color: #ffffff;
        line-height: 30px;
        height: 30px;
        margin: 10px auto 0;
        background: #ffffff;
      }

      .date {
        margin-top: 34px;
        color: #bfbfbf;
      }
    }
  }

  .addWrap {
    display: flex;
    padding: 0 55px 40px;
    flex-wrap: wrap;
    justify-content: start;

    .item {
      margin-top: 40px;
      margin-left: 15px;
      border: 1px solid #ffffff;
      width: 340px;
      height: 230px;
      padding: 28px 30px;
      border-radius: 10px;
      box-shadow: 0px 1px 4px 0px rgba(212, 224, 233, 0.5);
      background: #fff;
      color: #bfbfbf;

      .removeBox {
        float: right;
        .el-icon-more {
          font-size: 14px;
          cursor: pointer;
        }
      }

      .money {
        position: relative;
        top: 80px;
        display: flex;
        justify-content: start;
        font-size: 12px;
        color: #7a8287;
      }

      .nameBox {
        margin-top: -5px;
        margin-bottom: 5px;

        .name {
          width: fit-content;
          height: 28px;
          font-size: 20px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #1d1c1c;
          line-height: 28px;
          vertical-align: middle;
          word-break: break-all;
          margin-right: 10px;
        }

        .editIcon {
          font-size: 20px;
          vertical-align: middle;
          cursor: pointer;
        }
      }

      .number {
        font-family: "GothamSSm_medium";
        font-size: 12px;
        margin-top: 16px;
        color: #4f595f;
        text-align: start;
      }

      // &:nth-child(3n + 2) {
      //     margin-left: 2%;
      //     margin-right: 2%;
      // }
    }
    .item:hover {
      cursor: pointer;
      border: 1px solid #03bfc6;
    }
    .add {
      background: #f7f8fa;
      cursor: pointer;
      border: 1px dashed #869daa;
      text-align: center;

      .addIcon {
        margin-top: 58px;
        width: 24px;
        height: 24px;
      }

      .addText {
        color: #869daa;
        font-size: 14px;
      }
    }
  }
}
</style>
